<?php

namespace App\Http\Controllers;

use App\Models\StockCodes;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;

class LiXingRenController extends Controller
{
	public  $token;

	public function __construct()
	{
		$this->token = config('lixingren.token');
	}

	public function index()
    {
        return StockCodes::where('api', 'a')
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item['id'],
                    'code' => $item['code'],
                    'title' => $item['title'],
                    'pe_temp'=>$item['pe_temp'],
                    'pb_temp'=>$item['pb_temp'],
                    'index_temp' => $item['index_temperture'],
                ];
            })
            ->sortBy('index_temp')
            ->values();
    }


	protected function storeData($data)
	{
		foreach ($data as $value)
		{
			StockCodes::where('id',$value['id'])
				->update([
					'pe_temp' => $value['pe_temp'],
					'pb_temp' => $value['pb_temp'],
					'index_temperture'=> ($value['pe_temp']+$value['pb_temp'])/2,
					'computed_at'=> Carbon::now()
			]);
		}
	}

	protected function getOneIndexFundamental($code)
	{
		$reponse = Http::post('https://open.lixinger.com/api/a/index/fundamental',[
			'token' =>$this->token,
			'date'=>'latest',
			"stockCodes" => [
				$code
			],
			'metricsList'=>[
				"pe_ttm.y10.mcw",
				"pe_ttm.mcw",
				"pb.mcw",
				"pb.y10.mcw",
			]
		]);
		return $reponse ['data'];
	}
}
